from appium.webdriver.webdriver import WebDriver
from selenium.common.exceptions import NoSuchElementException


class BasePage:

    def __init__(self, driver: WebDriver = None):
        if driver:
            self.driver = driver
        else:
            raise SystemError

    def find(self, by, locator=None):
        if locator:
            ele = self.driver.find_element(by, locator)
        else:
            ele = self.driver.find_element(*by)

        return ele

    def find_all(self, by, locator):
        if locator:
            eles = self.driver.find_elements(by, locator)
        else:
            eles = self.driver.find_elements(*by)

        return eles

    def find_and_click(self, by, locator=None):
        self.swipe_and_find(by, locator).click()

    def find_and_input(self, text, by, locator=None):
        self.find(by, locator).send_keys(text)

    def get_element_text(self, by, locator=None):
        return self.find(by, locator).text

    def swipe_and_find(self, by, locator=None, retry=3):
        window_size = self.driver.get_window_rect()
        height = window_size["height"]
        width = window_size["width"]

        for i in range(retry):
            try:
                return self.find(by, locator)
            except:
                self.driver.swipe(width / 2, height * 0.9, width / 2, height * 0.1)

            if i == retry-1:
                raise NoSuchElementException(f"没有在{retry}次内找到指定元素")

    def back(self):
        self.driver.back()